package pub.cleangao.mybatis.template;

import com.jfinal.template.Engine;
import pub.cleangao.common.util.Resources;
import pub.cleangao.mybatis.meta.EntityInformation;
import pub.cleangao.mybatis.meta.TableDefinition;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;


/**
 * 加载MyBatis的映射文件(Mapper.xml)
 */
public class EnjoyEngine {

    private static final Engine engine = Engine.create("xml-assembler");

    static {
        engine.setDevMode(true);
    }

    /**
     * 获取模板内容
     *
     * @param mapperFullType    mapper的全路径名
     * @param tableDefinition   表定义
     * @param entityInformation 实体类定义
     */
    public static String getTemplateText(String mapperFullType, TableDefinition tableDefinition, EntityInformation entityInformation) {
        try (InputStream inputStream = Resources.getResourceAsStream("mapper-template/" + tableDefinition.getDialect().name() + ".xml")) {
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                result.write(buffer, 0, length);
            }
            return engine.getTemplateByString(result.toString(StandardCharsets.UTF_8))
                    .renderToStringBuilder(new HashMap<>() {{
                        put("mapper", mapperFullType);
                        put("table", tableDefinition);
                        put("entity", entityInformation);
                    }}).toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
